<template>
  <view class="daily-tasks">
    <view class="header">
      <text class="title">每日任务</text>
    </view>

    <view class="task-list">
      <view v-for="(task, index) in tasks" :key="index" class="task-item">
        <view class="task-content">
          <text class="task-title">{{ task.title }}</text>
          <text class="task-desc">{{ task.description }}</text>
        </view>
        <view class="task-actions">
          <view class="delete-btn" @tap="confirmDelete(index)">
            <text class="delete-icon">✕</text>
          </view>
        </view>
      </view>
    </view>

    <view class="add-task" v-if="!hasStudyTask || !hasReviewTask">
      <button @tap="showTaskDialog" type="primary" class="task-btn">添加今日任务</button>
    </view>
  </view>

  <!-- 自定义弹窗 -->
  <view class="custom-dialog" v-if="showDialog">
    <view class="dialog-mask" @tap="closeDialog"></view>
    <view class="dialog-content">
      <view class="dialog-header">
        <text class="dialog-title">选择任务类型</text>
      </view>
      <view class="dialog-body">
        <view class="task-type-list">
          <view
              class="task-type-item"
              :class="{ 'disabled': hasStudyTask }"
              @tap="!hasStudyTask && selectTaskType('study')"
          >
            <text class="task-icon">📚</text>
            <text class="task-name">学习任务</text>
            <text class="task-status" v-if="hasStudyTask">已添加</text>
          </view>
          <view
              class="task-type-item"
              :class="{ 'disabled': hasReviewTask }"
              @tap="!hasReviewTask && selectTaskType('review')"
          >
            <text class="task-icon">📝</text>
            <text class="task-name">复习任务</text>
            <text class="task-status" v-if="hasReviewTask">已添加</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {api} from "@/utils/request"

export default {
  data() {
    return {
      tasks: [],
      showDialog: false,
      remainingTime: 0,    // 剩余时间（秒）
      timer: null,         // 计时器
      wrongAnswers: 0,     // 错误答案计数
      userLevel: 1,        // 用户等级
      baseTime: 270,       // 基础时间 4分30秒
      timePerLevel: 30,    // 每级减少的时间（秒）
    }
  },
  computed: {
    hasStudyTask() {
      return this.tasks.some(task => task.type === 'study')
    },
    hasReviewTask() {
      return this.tasks.some(task => task.type === 'review')
    }
  },
  methods: {
    toggleTask(index) {
      this.tasks[index].completed = !this.tasks[index].completed
      // 保存到本地存储
      uni.setStorageSync('daily-tasks', this.tasks)

      // 如果任务完成，更新打卡日历
      if (this.tasks[index].completed) {
        const today = new Date()
        const dateStr = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`
        const completedDays = uni.getStorageSync('completed-days') || []
        if (!completedDays.includes(dateStr)) {
          completedDays.push(dateStr)
          uni.setStorageSync('completed-days', completedDays)
        }
      }
    },
    confirmDelete(index) {
      uni.showModal({
        title: '删除任务',
        content: '确定要删除这个任务吗？',
        confirmColor: '#ff4d4f',
        success: (res) => {
          if (res.confirm) {
            this.deleteTask(index)
          }
        }
      })
    },
    async deleteTask(index) {
      const res = await api.deleteDailyTask({
        "type": (this.tasks[index].type === "study") ? 1 : 0
      })

      if (res.code == 200){
        uni.showToast({
          title: '已删除任务',
          icon: 'success'
        })
        await this.getDailytTasks()
      }
    },
    showTaskDialog() {
      this.showDialog = true
    },
    closeDialog() {
      this.showDialog = false
    },
    selectTaskType(type) {
      this.showDialog = false
      if (type === 'study') {
        this.addStudyTask()
      } else {
        this.addReviewTask()
      }
    },
    async addStudyTask() {
      const foundItem = this.tasks.find(item => item.type === "study");
      if (foundItem) {
        uni.showToast({
          title: "只能新增一条今日学习单词计划",
          icon: 'error'
        });
      } else {
        uni.showModal({
          title: '设置学习目标',
          placeholderText: '请输入今日学习单词数',
          editable: true,
          confirmColor: '#07c160',
          success: async (res) => {
            if (res.confirm && res.content) {
              const wordCount = parseInt(res.content)
              if (isNaN(wordCount) || wordCount <= 0) {
                uni.showToast({
                  title: '请输入有效的数字',
                  icon: 'none'
                })
                return
              }
              const response = await api.addDailTask(
                  {
                    "learnWordNum": wordCount
                  }
              )
              if (response.code === 200) {
                uni.showToast({
                  title: '已添加学习任务',
                  icon: 'success'
                })
                await this.getDailytTasks()
              }
            }
          }
        })
      }
    },
    async addReviewTask() {
      uni.showModal({
        title: '设置复习目标',
        placeholderText: '请输入今日复习单词数',
        editable: true,
        confirmColor: '#07c160',
        success: async (res) => {
          if (res.confirm && res.content) {
            const wordCount = parseInt(res.content)
            if (isNaN(wordCount) || wordCount <= 0) {
              uni.showToast({
                title: '请输入有效的数字',
                icon: 'none'
              })
              return
            }
            const response = await api.addDailTask(
                {
                  "reviewsWordNum": wordCount
                }
            )
            if (response.code === 200) {
              uni.showToast({
                title: '已添加复习任务',
                icon: 'success'
              })
              await this.getDailytTasks()
            }
          }
        }
      })
    },
    async getDailytTasks() {
      const res = await api.getDailyTaskByDay()
      if (res.code === 200) {
        this.tasks = []
        if (res.result) {
          if (res.result.reviewsWordNum > 0){
            this.tasks.push({
              type: 'review',
              title: '今日复习',
              description: `目标：复习${res.result.reviewsWordNum}个单词`,
              completed: false,
            })
          }

          if (res.result.learnWordNum > 0){
            this.tasks.push({
              type: 'study',
              title: '今日学习',
              description: `目标：学习${res.result.learnWordNum}个新单词`,
              completed: false,
            })
          }
        }
      }
    },
  },
  onLoad() {
    // 从本地存储加载任务
    this.getDailytTasks()
  }
}
</script>

<style lang="scss">
.daily-tasks {
  padding: 40rpx;
  min-height: 100vh;
  background-image: linear-gradient(to bottom, #f8e5d7, #a8e6e2);

  .header {
    padding: 30rpx 0;

    .title {
      font-size: 40rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .task-list {
    margin-top: 30rpx;

    .task-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      background-color: #fff;
      border-radius: 16rpx;
      margin-bottom: 20rpx;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);

      .task-content {
        flex: 1;

        .task-title {
          font-size: 34rpx;
          color: #333;
          font-weight: 500;
          margin-bottom: 12rpx;
        }

        .task-desc {
          font-size: 26rpx;
          color: #666;
        }
      }

      .task-actions {
        display: flex;
        align-items: center;

        .checkbox-wrap {
          margin-right: 20rpx;
        }

        .delete-btn {
          width: 44rpx;
          height: 44rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #ffeaea;
          border-radius: 50%;

          &:active {
            opacity: 0.8;
          }

          .delete-icon {
            color: #ff4d4f;
            font-size: 24rpx;
            font-weight: bold;
          }
        }
      }
    }
  }

  .add-task {
    margin-top: 40rpx;
    padding: 0 20rpx;

    .task-btn {
      background: #07c160;
      border-radius: 12rpx;
      font-size: 32rpx;
      font-weight: 500;

      &:active {
        opacity: 0.9;
      }
    }
  }
}

.custom-dialog {
  .dialog-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 999;
  }

  .dialog-content {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 600rpx;
    background: #fff;
    border-radius: 20rpx;
    z-index: 1000;
    overflow: hidden;

    .dialog-header {
      padding: 30rpx;
      text-align: center;
      border-bottom: 1rpx solid #eee;

      .dialog-title {
        font-size: 34rpx;
        font-weight: bold;
        color: #333;
      }
    }

    .dialog-body {
      padding: 30rpx;

      .task-type-list {
        .task-type-item {
          display: flex;
          align-items: center;
          padding: 30rpx;
          background: #f8f8f8;
          border-radius: 12rpx;
          margin-bottom: 20rpx;

          &:last-child {
            margin-bottom: 0;
          }

          &.disabled {
            opacity: 0.5;
            pointer-events: none;
          }

          &:active {
            opacity: 0.8;
          }

          .task-icon {
            font-size: 40rpx;
            margin-right: 20rpx;
          }

          .task-name {
            flex: 1;
            font-size: 30rpx;
            color: #333;
            font-weight: 500;
          }

          .task-status {
            font-size: 24rpx;
            color: #999;
          }
        }
      }
    }
  }
}
</style> 